package org.example;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class DogDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void addDog(Dog dog) {
        String sql = "INSERT INTO dogs (name, age) VALUES (?, ?)";
        jdbcTemplate.update(sql, dog.getName(), dog.getAge());
    }

    public void updateDog(Dog dog) {
        String sql = "UPDATE dogs SET name=?, age=? WHERE id=?";
        jdbcTemplate.update(sql, dog.getName(), dog.getAge(), dog.getName().hashCode()); // Assuming name is unique for simplicity
    }

    public void deleteDog(String name) {
        String sql = "DELETE FROM dogs WHERE name=?";
        jdbcTemplate.update(sql, name);
    }

    public Dog getDog(String name) {
        String sql = "SELECT * FROM dogs WHERE name=?";
        return jdbcTemplate.queryForObject(sql, new Object[]{name}, new DogRowMapper());
    }

    public List<Dog> getAllDogs() {
        String sql = "SELECT * FROM dogs";
        return jdbcTemplate.query(sql, new DogRowMapper());
    }

    private static class DogRowMapper implements RowMapper<Dog> {
        @Override
        public Dog mapRow(ResultSet rs, int rowNum) throws SQLException {
            Dog dog = new Dog();
            dog.setName(rs.getString("name"));
            dog.setAge(rs.getInt("age"));
            return dog;
        }
    }
}
